package im.redis.collection;

import im.redis.client.operations.SortedSetOperation;

/**
 * 基于Redis的分布有序集合
 */
public class RSortedSet<E> {

	private RedisCollections collections;
	private final Class<E> clazz;
	private String keyName;
	private SortedSetOperation setOps;

	public RSortedSet(RedisCollections collections, String keyName, Class<E> clazz) {
		super();
		this.clazz = clazz;
		this.collections = collections;
		this.keyName = keyName;
		this.setOps = collections.getJedisTemplate().sortedSetOps();
	}

	public boolean add(E e, long score) {
		return setOps.zadd(keyName, score, collections.serialize(e));
	}

	public long score(E e) {
		Double score = setOps.zscore(keyName, collections.serialize(e));
		return score == null ? -1 : score.longValue();
	}

	/** 查看第一个元素 */
	public E peekFirst() {
		String json = setOps.peekFirst(keyName);
		if (json == null) {
			return null;
		}
		return collections.deserialize(json, clazz);
	}

	/** 移除并返回第一个元素 */
	public E first() {
		String json = setOps.first(keyName);
		return json == null ? null : collections.deserialize(json, clazz);
	}

	/** 查看最后一个元素 */
	public E peekLast() {
		String json = setOps.peekLast(keyName);
		if (json == null) {
			return null;
		}
		return collections.deserialize(json, clazz);
	}

	/** 移除并返回最后一个元素 */
	public E last() {
		String json = setOps.last(keyName);
		return json == null ? null : collections.deserialize(json, clazz);
	}

	public long size() {
		Long size = setOps.zcard(keyName);
		return size == null ? 0 : size;
	}

	public boolean contains(E e) {
		Double score = setOps.zscore(keyName, collections.serialize(e));
		return score != null;
	}
}
